<template>
  <view class="">
    <mescroll-uni
      ref="mescrollRef"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
      :down="downOption"
      :up="upOption"
      :height="`${systemInfo.windowHeight - top - systemInfo.statusBarHeight}px`"
    >
      <view class="order" v-for="res in dataList" :key="res.id" @click="onOrderClick(res)">
        <view class="top">
          <view class="left">
            <com-icon name="home" />
            <view class="store">{{ res.store }}</view>
            <com-icon name="arrow-right" color="var(--color-light)" />
          </view>
          <view class="right">{{ res.deal }}</view>
        </view>
        <view class="item" v-for="(item, index) in res.goodsList" :key="index">
          <view class="left">
            <image :src="item.goodsUrl" mode="aspectFill" />
          </view>
          <view class="content">
            <view class="title u-line-2">{{ item.title }}</view>
            <view class="type">{{ item.type }}</view>
            <view class="delivery-time">发货时间 {{ item.deliveryTime }}</view>
          </view>
          <view class="right">
            <view class="price com-text-price">
              {{ item.price | numberFormat }}
            </view>
            <view class="com-text-x">{{ item.number }}</view>
          </view>
        </view>
        <view class="order-summary">
          <view class="receiver-info" v-if="res.receiverInfo">
            收货人: {{ res.receiverInfo.name }} {{ res.receiverInfo.phone }}
          </view>
          <view class="total">
            共{{ totalNum(res.goodsList) }}件商品 
            <text v-if="res.payAmount && res.payAmount !== res.totalAmount">
              实付: <text class="total-price com-text-price">¥{{ res.payAmount.toFixed(2) }}</text>
            </text>
            <text v-else>
              合计: <text class="total-price com-text-price">¥{{ (res.totalAmount || 0).toFixed(2) }}</text>
            </text>
          </view>
        </view>
        <view class="bottom">
          <view class="order-info">
            <text class="order-no">订单号: {{ res.orderNo }}</text>
            <text class="create-time" v-if="res.createTime">{{ formatTime(res.createTime) }}</text>
          </view>
          <view class="order-actions">
            <view class="logistics btn" @click.stop="onViewLogistics(res)" v-if="res.deal === '待收货'">查看物流</view>
            <view class="pay btn primary" @click.stop="onPayOrder(res)" v-if="res.deal === '待付款'">立即付款</view>
            <view class="evaluate btn" @click.stop="onEvaluate(res)" v-if="res.deal === '待评价'">评价</view>
          </view>
        </view>
      </view>
    </mescroll-uni>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
import MescrollMoreItemMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mixins/mescroll-more-item.js'
import orderApi from '@/api/modules/order'
export default {
  name: 'Mescroll-Item',
  mixins: [MescrollMixin, MescrollMoreItemMixin],
  props: {
    top: {
      type: [Number, String],
      default: 0,
    },
    orderStatus: {
      type: [Number, String],
      default: '',
    },
  },
  computed: {
    ...mapState({
      systemInfo: (state) => state.app.systemInfo,
    }),
    // 价格小数
    priceDecimal() {
      return (val) => {
        if (val !== parseInt(val)) return val.slice(-2)
        else return '00'
      }
    },
    // 价格整数
    priceInt() {
      return (val) => {
        if (val !== parseInt(val)) return val.split('.')[0]
        else return val
      }
    },
  },
  data() {
    return {
      dataList: [],
      downOption: {
        auto: true, // 不自动加载 (mixin已处理第一个tab触发downCallback)
      },
      upOption: {
        auto: true, // 不自动加载
      },
      isInit: true, // 改变mixin中状态切换tabs时不用再次刷新
    }
  },
  methods: {
    async upCallback(page) {
      try {
        console.log('订单列表请求参数:', { 
          page: page.num - 1, 
          size: page.size,
          status: this.orderStatus 
        })
        
        const params = {
          page: page.num - 1, // API使用0基索引
          size: page.size
        }
        
        // 添加状态筛选参数
        if (this.orderStatus !== '' && this.orderStatus !== undefined) {
          params.status = this.orderStatus
        }
        
        const res = await orderApi.getList(params)
        console.log('订单列表响应:', res)
        
        // 处理订单数据，适配现有UI结构
        const orderData = this.formatOrderData(res || [])
        
        if (page.num == 1) {
          this.dataList = orderData
        } else {
          this.dataList = this.dataList.concat(orderData)
        }
        
        // 结束加载
        const totalPages = res.totalPages || Math.ceil((res.total || 0) / page.size) || 1
        this.mescroll.endByPage(orderData.length, totalPages)
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.mescroll.endErr()
      }
    },

    // 格式化订单数据以适配UI
    formatOrderData(orders) {
      return orders.map(order => ({
        id: order.orderId,
        orderNo: order.orderSn,
        store: this.$t('pages_user_order_components_order-item_msg_fc9efb87'),
        deal: this.getOrderStatusText(order.status),
        createTime: order.createTime,
        totalAmount: order.totalAmount,
        payAmount: order.payAmount,
        receiverInfo: {
          name: order.receiverName,
          phone: order.receiverPhone,
          address: `${order.receiverProvince}${order.receiverCity}${order.receiverDistrict}${order.receiverDetailAddress}`
        },
        goodsList: this.formatGoodsList(order.orderItemList || [])
      }))
    },

    // 格式化商品列表
    formatGoodsList(items) {
      return items.map(item => ({
        goodsUrl: item.pic || '/static/images/default-product.png',
        title: item.productName || this.$t('pages_product_detail_detail_msg_1fd1d5c5'),
        type: this.formatSpData(item.spData) || this.$t('pages_category_category_msg_064eb9e8'),
        deliveryTime: this.$t('pages_user_order_components_order-item_msg_c5941a2e'),
        price: item.salePrice || '0.00',
        number: item.quantity || 1,
        productId: item.productId,
        skuId: item.skuId,
        outProductId: item.outProductId,
        outSkuId: item.outSkuId
      }))
    },

    // 格式化规格数据
    formatSpData(spDataStr) {
      if (!spDataStr) return this.$t('pages_category_category_msg_064eb9e8')
      try {
        const spData = JSON.parse(spDataStr)
        return Object.entries(spData)
          .map(([key, value]) => `${key}: ${value}`)
          .join(', ')
      } catch (e) {
        console.error('解析spData失败:', e)
        return this.$t('pages_category_category_msg_064eb9e8')
      }
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        0: this.$t('pages_user_order_components_order-item_msg_818d7858'),
        1: this.$t('pages_user_order_components_order-item_msg_d8476e0a'), 
        2: this.$t('pages_user_order_components_order-item_msg_4933ca41'),
        3: this.$t('pages_user_order_components_order-item_msg_a48b2863'),
        4: this.$t('pages_event_grades_grades_msg_fad5222c'),
        5: this.$t('pages_user_event_detail_detail_msg_2111ccbb')
      }
      return statusMap[status] || this.$t('pages_album_album_msg_903b25f6')
    },
    // 总价
    totalPrice(item) {
      let price = 0
      item.map((val) => {
        price += parseFloat(val.price)
      })
      return price.toFixed(2)
    },
    // 总件数
    totalNum(item) {
      let num = 0
      item.map((val) => {
        num += val.number
      })
      return num
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },

    // 点击订单
    onOrderClick(order) {
      uni.navigateTo({
        url: `/pages/user/order/detail?id=${order.id}`
      })
    },

    // 查看物流
    onViewLogistics(order) {
      uni.showToast({
        title: this.$t('pages_user_order_components_order-item_desc_27ac0e1c'),
        icon: 'none'
      })
    },

    // 支付订单
    onPayOrder(order) {
      uni.showModal({
        title: this.$t('pages_user_order_components_order-item_msg_6536f5dc'),
        content: `是否支付订单 ${order.orderNo}？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: this.$t('pages_user_order_components_order-item_desc_cf0bed91'),
              icon: 'none'
            })
          }
        }
      })
    },

    // 评价订单
    onEvaluate(order) {
      uni.showToast({
        title: this.$t('pages_user_order_components_order-item_desc_83c8319e'),
        icon: 'none'
      })
    },
  },
}
</script>

<style scoped lang="scss">
.order {
  box-sizing: border-box;
  width: 710rpx;
  margin: 20rpx auto;
  padding: 20rpx;
  border-radius: 20rpx;
  background-color: $com-color-content-bg;
  font-size: 28rpx;

  .top {
    display: flex;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;

      .store {
        margin: 0 10rpx;
        font-size: 32rpx;
        font-weight: bold;
      }
    }

    .right {
      color: $com-color-warning-dark;
    }
  }

  .item {
    display: flex;
    margin: 20rpx 0 0;

    .left {
      margin-right: 20rpx;

      image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 10rpx;
      }
    }

    .content {
      .title {
        font-size: 28rpx;
        line-height: 50rpx;
      }

      .type {
        margin: 10rpx 0;
        color: $com-color-tips;
        font-size: 24rpx;
      }

      .delivery-time {
        color: $com-color-warning;
        font-size: 24rpx;
      }
    }

    .right {
      margin-left: 10rpx;
      padding-top: 20rpx;
      text-align: right;
    }
  }

  .order-summary {
    margin-top: 20rpx;
    
    .receiver-info {
      font-size: 24rpx;
      color: $com-color-tips;
      margin-bottom: 8rpx;
      padding-bottom: 8rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }

    .total {
      font-size: 24rpx;
      text-align: right;

      .total-price {
        font-size: 32rpx;
        font-weight: bold;
      }
    }
  }

  .bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 40rpx;
    padding: 0 10rpx;

    .order-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .order-no {
        font-size: 24rpx;
        color: $com-color-tips;
      }

      .create-time {
        font-size: 22rpx;
        color: $com-color-light;
      }
    }

    .order-actions {
      display: flex;
      gap: 20rpx;
    }

    .btn {
      width: 140rpx;
      border: 2rpx solid $com-color-border;
      border-radius: 26rpx;
      color: $com-color-info-dark;
      font-size: 26rpx;
      line-height: 52rpx;
      text-align: center;

      &.primary {
        border-color: #007aff;
        color: #007aff;
        background: rgba(0, 122, 255, 0.1);
      }
    }

    .evaluate {
      border-color: $com-color-warning-dark;
      color: $com-color-warning-dark;
    }

    .logistics {
      border-color: $com-color-success;
      color: $com-color-success;
    }
  }
}
</style>
